# -*- coding: utf-8 -*-
"""
Module Description:
Date: 2021/02/24
Author: chenmurong
"""
from pyshare.core.context import temporary_ctx
from pyshare.bll.utils.share.base_cache_info import BaseCacheInfo
from pyshare.redis_cache.share.alliance_cache import alliance_cache
from pyshare.dal.repository_impl import AllianceRepository


class AllianceInfo(BaseCacheInfo):

    default_var = {'id': 0, 'name': "", "server_id": 1}


class AllianceInfoCacheUtil(object):
    """
    联盟信息缓存功能
    """

    @classmethod
    def set_alliance_info(cls, alliance_info_dict):
        """
        设置联盟信息缓存
        :param alliance_info_dict: {alliance_id: AllianceInfo}
        :return:
        """
        alliance_cache.set_many_alliance_cache(alliance_info_dict)

    @classmethod
    def refresh_alliance_info(cls, server_dict):
        """
        刷新联盟信息
        :param server_dict: {server_id: alliance_id_list}
        :return:
        """
        cls.get_alliance_info_from_db(server_dict)

    @classmethod
    def get_alliance_info_from_cache(cls, alliance_id_list):
        """
        从缓存获取联盟信息
        :param alliance_id_list:
        :return:
        """
        alliance_dict = {}
        not_find = []
        data_list = alliance_cache.get_many_alliance_cache(alliance_id_list)
        for alliance_id, data in zip(alliance_id_list, data_list):
            if data:
                alliance_dict.update({alliance_id: AllianceInfo(**data)})
            else:
                not_find.append(alliance_id)

        return alliance_dict, not_find

    @classmethod
    def get_alliance_info_from_db(cls, server_dict):
        """
        从db获取联盟信息
        :param server_dict: {server_id: alliance_id_list}
        :return:
        """
        alliance_info_obj_dict = {}
        set_alliance_dict = {}
        for server_id, alliance_id_list in server_dict.iteritems():
            if not alliance_id_list:
                continue
            # 指定访问的区服
            with temporary_ctx(server_id=server_id):
                fields = AllianceInfo().get_fields()
                for alliance in AllianceRepository.filter_by_id_list(alliance_id_list, 'Id', 'Name'):
                    alliance_info = {}
                    for field in fields:
                        if field == "server_id":
                            alliance_info[field] = server_id
                        else:
                            alliance_info[field] = getattr(alliance, field)
                    alliance_info_obj_dict.update({alliance.id: AllianceInfo(**alliance_info)})
                    set_alliance_dict.update({alliance.id: alliance_info})
        # 更新缓存
        cls.set_alliance_info(set_alliance_dict)
        return alliance_info_obj_dict

    @classmethod
    def get_alliance_information(cls, server_dict):
        """
        先从缓存获取，取不到在从db获取
        :param server_dict: {server_id: [alliance_id]}
        :return: {rid: AllianceInfo}
        """
        all_alliance_id_list = sum(server_dict.values(), [])
        alliance_info_obj_dict, not_find_list = cls.get_alliance_info_from_cache(all_alliance_id_list)
        for server_id, alliance_id_list in server_dict.iteritems():
            if not alliance_id_list:
                continue
            not_find_set = set(not_find_list) & set(alliance_id_list)
            if not not_find_set:
                continue
            # 缓存中未获取数据，从DB获取
            alliance_info_obj_dict.update(cls.get_alliance_info_from_db({server_id: list(not_find_set)}))
        return alliance_info_obj_dict


